const db = require('./db')
const inquirer = require('inquirer');


module.exports.add = async (title) => {
  //读取之前的任务
  const list = await db.read()
  //往里面添加一个title任务
  list.push({title, done: false})
  //存储认为到文件
  await db.write(list)

}
//文件操作都是异步的
module.exports.clear = async () => {
  await db.write([]) //写入了空数组
}

function markAsDone(list,index){
  list[index].done = true
  db.write(list)
}

function markAsUndone(list,index){
  list[index].done = false
  db.write(list)
}

function updateTitle(list,index){
  inquirer
    .prompt({
      type: 'input',
      name: 'title',
      message: '新标题',
      default: list[index].title,
      choices: [
        {name: '退出', value: 'quit'},
        {name: '已完成', value: 'markAsDone'},
        {name: '未完成', value: 'markAsUndone'},
        {name: '改标题', value: 'updateTitle'},
        {name: '删除', value: 'remove'},
      ]
    }).then((answer) => {
    list[index].title = answer.title
    db.write(list)
  })
}

function remove(list,index){
  list.splice(index, 1)
  db.write(list)
}


function askForAction(list,index) {
  const actions={  //函数名作为key
    markAsUndone,
    markAsDone,
    updateTitle,
    remove
  }
  //选中了一个任务
  inquirer
    .prompt({
      type: 'list',
      name: 'action',
      message: '请选择操作',
      choices: [
        {name: '退出', value: 'quit'},
        {name: '已完成', value: 'markAsDone'},
        {name: '未完成', value: 'markAsUndone'},
        {name: '改标题', value: 'updateTitle'},
        {name: '删除', value: 'remove'},
      ]
    }).then((answer2) => { //如果选择成功就会得到一个answer
    const action=actions[answer2.action]
    action&&action(list,index)  //存在就执行这个方法
  }, () => {

  })

}

function printTasks(list) {
  //打印之前的任务
  //printTasks
  list.forEach((task, index) => {
    console.log(`${task.done ? '[√]' : '[_]'} ${index + 1} - ${task.title}`)
  })

  inquirer
    .prompt(
      {
        type: 'list',
        name: 'index',
        message: '选择你想操作的任务',
        choices: [{name: '退出', value: '-1'}, ...list.map((task, index) => {
          return {name: `${task.done ? '[√]' : '[_]'} ${index + 1} - ${task.title}`, value: index.toString()}
        }), {name: '+创建任务', value: '-2'}]
      },
    ).then((answers) => {
    const index = parseInt(answers.index)
    if (index >= 0) {
      askForAction(list,index)
    } else if (index === -2) {
      askForCreateTask(list)
    }
  });
}

function askForCreateTask(list){
  //创建任务
  inquirer.prompt({
    type: 'input',
    name: 'title',
    message: '输入任务标题',
  }).then((answer) => {
    list.push({
      title: answer.title,
      done: false
    })
    db.write(list)
  })
}



//用户直接执行 node cli.js 就会执行这个
module.exports.showAll = async (title) => {
  //读取之前的任务
  const list = await db.read()
    printTasks(list)
}
